package com.treeliked;

import com.treeliked.config.JsonProvider;
import com.treeliked.util.Constant;
import org.glassfish.grizzly.http.server.HttpServer;
import org.glassfish.jersey.grizzly2.httpserver.GrizzlyHttpServerFactory;
import org.glassfish.jersey.media.multipart.MultiPartFeature;
import org.glassfish.jersey.server.ResourceConfig;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.URI;

/**
 * 客户端模拟操作
 *
 * @author lqs2
 * @date 2018/11/29, Thu
 */
public class Client {

    private static Logger log = LoggerFactory.getLogger(Client.class);

    private static HttpServer server;

    static {
        // 启动http服务
        server = startServer();
    }

    public static void main(String[] args) {

        log.info("Jersey server started with WADL available at {}， type any key to stop it.", Constant.BASE_URI);

        log.info("使用帮助");

        log.info("\t文件夹使用帮助");
        log.info("\t\t创建文件夹url：");
        log.info("\t\t\t在当前项目目录下新建一个hello文件夹：{}", "http://localhost:8080/fileos/folder/mkdir/hello");
        log.info("\t\t\t在当前项目hello目录下新建一个world文件夹：{}", "http://localhost:8080/fileos/folder/mkdir/hello/world");
        log.info("\t\t删除文件夹url：");
        log.info("\t\t\t删除当前项目目录下的hello文件夹：{}", "http://localhost:8080/fileos/folder/rm/hello");
        log.info("\t\t\t删除当前项目目录hello文件夹下的world文件夹：{}", "http://localhost:8080/fileos/folder/rm/hello/world");
        log.info("\t\t查看文件夹url：");
        log.info("\t\t\t查看当前项目目录下hello文件夹的内容：{}", "http://localhost:8080/fileos/folder/ls/hello");
        log.info("\t\t\t查看当前项目目录下hello文件夹下world的内容：{}", "http://localhost:8080/fileos/folder/ls/hello/world");

        log.info("\t文件使用帮助");
        log.info("\t\t上传文件url：");
        log.info("\t\t\t上传文件，根据提示操作：{}", "http://localhost:8080/fileos/file/upload");
        log.info("\t\t下载文件url：");
        log.info("\t\t\t下载当前项目hello文件夹下的world.txt文件: {}", "http://localhost:8080/fileos/file/download/hello/world.txt");


        String cmd = readCommand();
        log.info(cmd);
        server.shutdown();
        log.info("{}", "服务结束");
    }


    private static HttpServer startServer() {
        final ResourceConfig rc = new ResourceConfig().packages("com.treeliked.resource");
        // 注册提供json服务
        rc.register(JsonProvider.class);
        // 提供文件功能
        rc.register(MultiPartFeature.class);
        return GrizzlyHttpServerFactory.createHttpServer(URI.create(Constant.BASE_URI), rc);

    }

    /**
     * 从控制台读取命令
     **/
    private static String readCommand() {
        try {
            BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
            return reader.readLine();
        } catch (IOException e) {
            log.error("IO异常", e);
        }
        return null;
    }

}
